package cn.kailangtu.commontools;

import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;

import java.util.List;

import cn.kailangtu.commonevents.data.DataBean;

public class KeyboardUtils {
    //static char[] numberElement = new char[]{'0','1','2','3','4','5','6','7','8','9','-','.'};
    static String numberElement="1234567890-.";
    public static String getRealNumberValue(String source)
    {
        String result = "";
        char[] sourceCharArr = source.toCharArray();
        for(char c : sourceCharArr)
        {
            if(numberElement.indexOf(c)> -1)
            {
                result +=c;
            }
        }
        return result;
    }

    public static String getCurrentNumberValue(TextView view)
    {
        String result = "";

        if(view != null)
        {
            String source = view.getText().toString();
            result = KeyboardUtils.getRealNumberValue(source);
        }

        return result;
    }

    public static String getUnit(TextView view){
        String result = "";


        if(view != null)
        {
            String source = view.getText().toString();
            String result2 = KeyboardUtils.getRealNumberValue(source);
            if(source.length()  != result.length())
            {
                result = source.substring(result2.length());
            }
        }

        return result;
    }

    public static void setNewValue(TextView view, String newValue, List<DataBean<Integer>> dataBean,int processType){

        if(dataBean != null && dataBean.size()>0){
            for(int i = 0;i < dataBean.size();i++){
                if(dataBean.get(i).getValue().toString().equals(newValue))
                {
                    view.setText(dataBean.get(i).getLabel());
                    break;
                }
            }
        }
        else {
            String unit = getUnit(view);
            if(processType == 2){
                view.setText( String.format("%.1f", Float.valueOf(newValue) / 10) + unit);;
            }
            else {
                view.setText(newValue + unit);
            }
        }
    }

    public static void sendKeyboardEvent(int keyCode)
    {
        try{
            String keyCommand = "input keyevent "+keyCode;
            Runtime.getRuntime().exec(keyCommand);
            Log.e("KEYBOARD",keyCommand);
        }
        catch(Exception e)
        {
            Log.e("KEYBOARD",e.getMessage());
            e.printStackTrace();
        }
    }
}
